import axios from "./axios/axios.min.js";

function handBaseURL(config) {
  let self_baseURL = uni.getStorageSync("ip") || "http://127.0.0.1:8181";

  // 处理掉地址最后面的斜杠
  if (self_baseURL.slice(-1) == "/") {
    self_baseURL = self_baseURL.slice(0, -1);
  }
  config.url = self_baseURL + config.url;
}


const service = axios.create({
  timeout: 120000, 
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    config.adapter = uniAdapter;

    // 处置基础URL
    handBaseURL(config);

    // get请求映射params参数
    handParams(config);

    // 处理token
    handToken(config);

    return config;
  },
  (error) => {
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code == 401) {
      //重新登录
      uni.$u.toast("获取用户信息失败");
    }
    return res;
  },
  (error) => {
    console.log("err" + error); // for debug
    return Promise.reject(error);
  }
);

export default service;
const request = service;

export function get(url, params, type) {
  return request({
    url: url,
    method: "GET",
    params: params,
    type: type,
  });
}

export function post(url, data, type) {
  return request({
    url: url,
    method: "post",
    data: data,
    type: type,
  });
}

export function put(url, data) {
  return request({
    url: url,
    method: "put",
    data: data,
  });
}

export function del(url, data) {
  return request({
    url: url,
    method: "delete",
    data: data,
  });
}

export function download(url, data, method = "post") {
  return request({
    url: url,
    method: method,
    data: data,
    responseType: "blob",
  }).then((res) => {
    let blob = new Blob([res.data]);
    let headers = res.headers;
    const contentDisposition = headers["content-disposition"];
    let fileName = window.decodeURI(contentDisposition.split("filename=")[1]);

    if ("download" in document.createElement("a")) {
      let link = document.createElement("a");
      link.href = window.URL.createObjectURL(blob); // 创建下载的链接
      link.download = fileName; // 下载后文件名
      link.style.display = "none";
      document.body.appendChild(link);
      link.click(); // 点击下载
      window.URL.revokeObjectURL(link.href); // 释放掉blob对象
      document.body.removeChild(link); // 下载完成移除元素
    } else {
      // IE10+下载
      window.navigator.msSaveBlob(blob, fileName);
    }
  });
}

const handParams = (config) => {
  if (config.method === "get" && config.params) {
    let url = config.url + "?";
    for (const propName of Object.keys(config.params)) {
      const value = config.params[propName];
      var part = encodeURIComponent(propName) + "=";
      if (value !== null && typeof value !== "undefined") {
        if (typeof value === "object") {
          for (const key of Object.keys(value)) {
            const params = propName + "[" + key + "]";
            var subPart = encodeURIComponent(params) + "=";
            url += subPart + encodeURIComponent(value[key]) + "&";
          }
        } else {
          url += part + encodeURIComponent(value) + "&";
        }
      }
    }
    url = url.slice(0, -1);
    config.params = {};
    config.url = url;
  }
};

const uniAdapter = (config) => {
  if (!uni) {
    throw new Error("please use this in uni-app project!");
  }
  return new Promise((resolve, reject) => {
    const { headers, data, params } = config;
    const uniConfig = {
      ...config,
      // url: baseURL + url,
      header: headers,
    };

    if (data || params) {
      try {
        uniConfig.data = JSON.parse(data || params);
      } catch (e) {
        uniConfig.data = data || params;
      }
    }
    uni.request({
      ...uniConfig,
      success(res) {
        resolve({
          ...res,
          headers: res.header,
        });
      },
      fail(res) {
        reject({
          ...res,
          headers: res.header,
        });
      },
    });
  });
};

function handToken({ headers, url }) {
  if (url.includes("/login/noCode")) {
    return;
  }

  const token = uni.getStorageSync("token") || "";
  if (token) {
    headers["Authorization"] = token;
  }
}
